package com.example;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.experimental.Accessors;

@Data
@Accessors(chain = true)
public class Student {
    private String name;
    private int score;

    public static void main(String[] args) {
        /*
         * 将JSON字符串转为Bean对象
         */
        System.out.println("---------将JSON字符串转为Bean对象--------");
        String jsonStudent = "{name:'yolo',score:90}";
        Student s1 = JSON.parseObject(jsonStudent, Student.class);
        System.out.println(jsonStudent);
        System.out.println(s1);

        /*
         * 将JSON字符串转为Bean对象
         */
        System.out.println("-----------将对象转化为Json字符串------");
        Student s2 = new Student().setName("yolo").setScore(98);
        String s = JSON.toJSONString(s2);
        System.out.println(s2);
        System.out.println(s);


        System.out.println("-----------其他的用法------");
        String str = "{\"name\":\"Yolo\",\"Address\":\"Beijing\"}";
        JSONObject jsonObject = JSON.parseObject(str);
        System.out.println(jsonObject.toString());
        System.out.println(jsonObject.getString("name"));
        System.out.println(str);

        String str2 = "{\"name\":\"Yolo\",\"Address\":\"Beijing\", \"data\":{\"id\": 123}}";
        JSONObject jsonObject2 = JSON.parseObject(str2);
        System.out.println(jsonObject2.getString("data"));
        System.out.println(JSON.parseObject(jsonObject2.getString("data")).getString("id"));

        String str3 = "{\"name\":\"Yolo\",\"Address\":\"Beijing\", \"data\":[{\"id\": 123},{\"id\": 345}]}";
        JSONObject jsonObject3 = JSON.parseObject(str3);
        System.out.println(jsonObject3.toString());
        System.out.println(jsonObject3.toJSONString());
        System.out.println("data " + jsonObject3.getString("data"));
        JSONArray data = JSON.parseArray(jsonObject3.getString("data"));
        for (Object d: data) {
            System.out.println(d);
            System.out.println(JSON.parseObject(d.toString()).getString("id"));
            System.out.println(JSON.parseObject(String.valueOf(d)).getString("id"));
        }
    }
}

